package com.health.system.common.utils;


import cn.hutool.http.HttpRequest;
import com.health.system.dto.IpInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;

/**
 */
@Slf4j
public class IpUtil {
    private IpUtil() {

    }

    private static String getCurrentIp() {
        String unknown = "unknown";

        HttpServletRequest request = ServletRequestUtil.getRequest();
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getIpAddress() {
        return getInfo().getIp();
    }

    public static String getIpSource() {
        StringBuilder result = new StringBuilder();

        IpInfoDTO info = getInfo();
        String country = info.getCountry();
        if (StringUtils.isNotBlank(country)) {
            result.append(country);
        }
        String isp = info.getIsp();
        if (StringUtils.isNoneBlank(isp)) {
            result.append("|").append(isp);
        }
        String province = info.getProvince();
        if (StringUtils.isNoneBlank(province)) {
            result.append("|").append(province);
        }
        String city = info.getCity();
        if (StringUtils.isNoneBlank(city)) {
            result.append("|").append(city);
        }
        String area = info.getArea();
        if (StringUtils.isNoneBlank(area)) {
            result.append("|").append(area);
        }

        return result.toString();
    }

    private static IpInfoDTO getInfo() {
        String ipURI = "https://ip.useragentinfo.com/json?ip=" + getCurrentIp();

        String body = HttpRequest.get(ipURI)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .execute()
                .body();

        return JsonUtil.convert(body, IpInfoDTO.class);

    }
}
